package com.xxxx.rpc.service;

import com.xxxx.api.pojo.*;
import com.xxxx.api.service.CartService;
import com.xxxx.rpc.mapper.GoodsImagesMapper;
import com.xxxx.rpc.mapper.GoodsMapper;
import io.lettuce.core.RedisClient;
import io.lettuce.core.RedisURI;
import io.lettuce.core.api.StatefulRedisConnection;
import io.lettuce.core.api.sync.RedisCommands;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.time.temporal.ChronoUnit;
import java.util.*;

/**
 * @author nathan-wang on 2020-11-06
 */
@Service(version = "1.0")
public class CartServiceImpl implements CartService {
    @Autowired
    private GoodsMapper goodsMapper;
    @Autowired
    private GoodsImagesMapper goodsImagesMapper;

    /**
     * addCart
     *
     * @param userId
     * @param goodsId
     * @param goodsNum
     * @return
     */
    public  ResultInfo addCart(String userId, String goodsId, String goodsNum) {
        //存入redis
        RedisURI redisUri = RedisURI.builder()  //创建连接
                .withHost("192.168.10.100")
                .withPort(6379)
                .withDatabase(0)
                .withPassword("root")
                .withTimeout(Duration.of(10, ChronoUnit.SECONDS))
                .build();
        RedisClient client = RedisClient.create(redisUri);//client
        StatefulRedisConnection<String, String> connection = client.connect(); // 获取一个连接
        RedisCommands<String, String> commands = connection.sync(); // 获取同步指令集
        //拼接cart:userId ; 例如: cart :1001即用户1001的购物车
        commands.hset(userId, goodsId, goodsNum);
        ResultInfo resultInfo = new ResultInfo();
        resultInfo.setMsg("操作成功!");
        return resultInfo;
    }

    /**
     * getCartNum
     *
     * @param admin
     * @return
     */
    public Integer getCartNum(Admin admin) {
        RedisURI redisUri = RedisURI.builder()  //创建连接
                .withHost("192.168.10.100")
                .withPort(6379)
                .withDatabase(0)
                .withPassword("root")
                .withTimeout(Duration.of(10, ChronoUnit.SECONDS))
                .build();
        RedisClient client = RedisClient.create(redisUri);//client
        StatefulRedisConnection<String, String> connection = client.connect(); // 获取一个连接
        RedisCommands<String, String> commands = connection.sync(); // 获取同步指令集
        Short adminId = admin.getAdminId();
        String userId = String.valueOf(adminId);
        Map<String, String> map = commands.hgetall(userId);
//        Set<String> strings = map.keySet();
        Collection<String> values = map.values();
        Integer sum = 0;
        for (String temp : values) {
            int i = Integer.parseInt(temp);
            sum += i;
        }
        return sum;
    }

    /**
     * cleanMyCart
     *
     * @param admin
     */
    public void cleanMyCart(Admin admin) {
        Short adminId = admin.getAdminId();
        String userId = String.valueOf(adminId);
        //存入redis
        RedisURI redisUri = RedisURI.builder()  //创建连接
                .withHost("192.168.10.100")
                .withPort(6379)
                .withDatabase(0)
                .withPassword("root")
                .withTimeout(Duration.of(10, ChronoUnit.SECONDS))
                .build();
        RedisClient client = RedisClient.create(redisUri);//client
        StatefulRedisConnection<String, String> connection = client.connect(); // 获取一个连接
        RedisCommands<String, String> commands = connection.sync(); // 获取同步指令集
        //清空购物车
        commands.del(userId);
        connection.close(); // 关闭连接
        client.shutdown(); // 关闭所有连接
    }

    /**
     * getCartList
     *
     * @param admin
     * @return
     */
    public CartResult getCartList(Admin admin) {
        Short adminId = admin.getAdminId();
        String userId = String.valueOf(adminId);
        //取redis
        RedisURI redisUri = RedisURI.builder()  //创建连接
                .withHost("192.168.10.100")
                .withPort(6379)
                .withDatabase(0)
                .withPassword("root")
                .withTimeout(Duration.of(10, ChronoUnit.SECONDS))
                .build();
        RedisClient client = RedisClient.create(redisUri);//client
        StatefulRedisConnection<String, String> connection = client.connect(); // 获取一个连接
        RedisCommands<String, String> commands = connection.sync(); // 获取同步指令集
        //取出
        Map<String, String> cartMap = commands.hgetall(userId);
        //keys——goodsId;查出goodsName,marketPrice
//        Set<String> keySet = cartMap.keySet();
//        //values——goodsNum
//        Collection<String> values = cartMap.values();
        List<Cart> list = new ArrayList<>();
        for (Map.Entry<String, String> entry : cartMap.entrySet()) {
            String goodsid = entry.getKey();
            Integer goodsId = Integer.parseInt(goodsid);
            String goodsnum = entry.getValue();
            Goods goods = goodsMapper.selectByPrimaryKey(goodsId);
            String goodsName = goods.getGoodsName();
            BigDecimal marketPrice = goods.getMarketPrice();
            Integer goodsNum = Integer.parseInt(goodsnum);
            Cart cart = new Cart();
            //goodsId查imageUrl
            GoodsImages goodsImages = goodsImagesMapper.queryByGoodsId(goodsId);
            String originalImg = goodsImages.getImageUrl();
            cart.setOriginalImg(originalImg);
            cart.setGoodsName(goodsName);
            cart.setMarketPrice(marketPrice);
            cart.setGoodsNum(goodsNum);
            SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM--dd HH:mm:ss");
            cart.setAddTime(simpleDateFormat.format(new Date()));
            list.add(cart);
        }
        //totalPrice
        BigDecimal totalPrice=new BigDecimal("0.00");
        BigDecimal price = list.stream().map(
                e->e.getMarketPrice().multiply(new BigDecimal(String.valueOf(
                        e.getGoodsNum()
                )))).reduce(BigDecimal.ZERO,BigDecimal::add);
        CartResult cartResult = new CartResult(list,price);
        return cartResult;
    }
}
